/**
 * author:wuhong
 * date:2019/6/13
 * 申请指定权限的工具类
 */
var permission={
  /**
   * 申请非必须权限
   * param:所需权限
   */
  auth(per){
    // 获取用户信息
    if(!per){
      return
    }
    let msg = per.substring(per.indexOf('.'), per.length)
    return this.getSetting4Promise(per).then((res) => {
      if (!res.authSetting[per]) {
        return this.authorize4Promise(per)
      }
    })
  },
  /**
   * 申请必须权限
   * param: per 权限   desc 描述
   */
  authMust(per,desc){
    desc = desc || '请求获取' + per + '的权限'
    if (!per) {
      return
    }
    return this.getSetting4Promise(per).then((res)=>{
      if (!res.authSetting[per]) {
        return this.authorize4Promise(per).catch(()=>{
          return new Promise((resolve,reject)=>{
            wx.showModal({
              title: '权限申请',
              content: desc,
              success: (res) => {
                if (res.confirm) {
                  this.opensetting4Promise(per).then(()=>{
                    resolve()
                  }).catch(() => {
                    this.authMust(per, desc)
                  })
                } else {
                  this.authMust(per, desc)
                }
              }
            })
          })
          
        })
      }else{
        return Promise.resolve()
      }
    })
  },
  opensetting4Promise(per){
    return  new Promise((resolve,reject)=>{
      wx.openSetting({
        success: function(res) {
          console.log('openSetting',res)
          if (res.authSetting[per]){
            resolve(res)
          }else{
            reject(res)
          }
        },
        fail: function(res) {
          reject(res)
        },
      })
    })
  },
  authorize4Promise(permission){
    return new Promise((resolve,reject)=>{
      wx.authorize({
        scope: permission,
        success: function (res) {
          resolve(res)
        },
        fail: function (res) {
          reject(res)
         },
      })
    })
  },
  getSetting4Promise(per){
    return new Promise((resolve,reject)=>{
      wx.getSetting({
        success: function(res) {
          // console.log(res)
          resolve(res)
          
        },
        fail: function(res) {
          console.error(res)
          reject(res)
        },
      })
    })
  }
}
module.exports = permission